package test.top1.com.atguigu.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple4;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;
import test.top1.com.atguigu.bean.TrafficPageViewBean;
import test.top1.com.atguigu.utils.DateFormatUtil;
import test.top1.com.atguigu.utils.MyClickHouseUtil;
import test.top1.com.atguigu.utils.MyKafkaUtil;

import java.time.Duration;

/**
 * ClassName: Dws02_TrafficVcChArIsNewPageViewWindow
 * Package: test.top1.com.atguigu.app.dws
 * Description:
 *
 * @Author ChenJun(有志男青年)
 * @Create 2023/5/6 20:55
 * @Version 1.0
 */

//数据流：web/app -> 日志服务器(log) -> Flume -> Kafka(ODS) -> FlinkApp -> Kafka(DWD) -> FlinkApp -> ClickHouse(DWS)
//程 序：Mock -> log - > Flume -> Kafka(ZK) -> BaseLogApp -> Kafka(ZK) -> Dws02_TrafficVcChArIsNewPageViewWindow -> ClickHouse(ZK)
public class Dws02_TrafficVcChArIsNewPageViewWindow {
    public static void main(String[] args) throws Exception {

        //TODO 1.获取运行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        // TODO 配置环境信息生产环境得有

//         env.enableCheckpointing(3000L, CheckpointingMode.EXACTLY_ONCE);
//        env.getCheckpointConfig().setCheckpointTimeout(60 * 1000L);
//        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(3000L);
//        env.getCheckpointConfig().enableExternalizedCheckpoints(
//                CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION
//        );
//        env.setRestartStrategy(RestartStrategies.failureRateRestart(
//                10, Time.of(1L, TimeUnit.DAYS), Time.of(3L, TimeUnit.MINUTES)
//        ));
//        env.setStateBackend(new HashMapStateBackend());
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
//        System.setProperty("HADOOP_USER_NAME", "atguigu")

        //TODO 2.读取kafka dwd 层页面数据
        DataStreamSource<String> kafkaDS = env.fromSource(MyKafkaUtil.getKafkaSource("dwd_traffic_page_log",
                        "dws02_traffic_vc_ch_ar_isnew_pageview_221109"),
                WatermarkStrategy.noWatermarks(), "kafka-source");

        //TODO 3.转换为json对象
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaDS.map(JSON::parseObject);

        //TODO 4.按照mid分组
        KeyedStream<JSONObject, String> keyedByMidDS = jsonObjDS.keyBy(json -> json.getJSONObject("common").getString("mid"));

        //TODO 5.去重mid，转换为Javabean对象
        SingleOutputStreamOperator<TrafficPageViewBean> trafficPageViewByMidDS =
                keyedByMidDS.map(new RichMapFunction<JSONObject, TrafficPageViewBean>() {

            private ValueState<String> valueState;

            @Override
            public void open(Configuration parameters) throws Exception {
                ValueStateDescriptor<String> stateDescriptor = new ValueStateDescriptor<>("mid-state", String.class);

                //设置ttl
                StateTtlConfig stateTtlConfig = new StateTtlConfig.Builder(Time.days(1))
                        .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                        .build();
                stateDescriptor.enableTimeToLive(stateTtlConfig);

                valueState = getRuntimeContext().getState(stateDescriptor);
            }

            @Override
            public TrafficPageViewBean map(JSONObject value) throws Exception {

                //取出状态数据
                String lastDt = valueState.value();

                long uvCt = 0L;
                String curDt = DateFormatUtil.toDate(value.getLong("ts"));

                if (lastDt == null || !lastDt.equals(curDt)) {
                    uvCt = 1L;
                    valueState.update(curDt);
                }

                //获取common信息
                JSONObject common = value.getJSONObject("common");

                return new TrafficPageViewBean("", "",
                        common.getString("vc"),
                        common.getString("ch"),
                        common.getString("ar"),
                        common.getString("is_new"),
                        common.getString("sid"),
                        uvCt,
                        0L,
                        1L,
                        value.getJSONObject("page").getLong("during_time"),
                        value.getLong("ts"));
            }
        });

        //TODO 6.按照sid分组
        KeyedStream<TrafficPageViewBean, String> keyedBySidDS =
                trafficPageViewByMidDS.keyBy(TrafficPageViewBean::getSid);

        //TODO 7.去重sid
        SingleOutputStreamOperator<TrafficPageViewBean> trafficPageViewBySidDS =
                keyedBySidDS.map(new RichMapFunction<TrafficPageViewBean, TrafficPageViewBean>() {

            private ValueState<String> valueState;

            @Override
            public void open(Configuration parameters) throws Exception {
                ValueStateDescriptor<String> stateDescriptor = new ValueStateDescriptor<>("sid-state", String.class);

                StateTtlConfig ttlConfig = new StateTtlConfig.Builder(Time.hours(1))
                        .setUpdateType(StateTtlConfig.UpdateType.OnReadAndWrite)
                        .build();

                stateDescriptor.enableTimeToLive(ttlConfig);
                valueState = getRuntimeContext().getState(stateDescriptor);

            }

            @Override
            public TrafficPageViewBean map(TrafficPageViewBean value) throws Exception {

                String state = valueState.value();

                if (state == null) {
                    value.setSvCt(1L);
                    valueState.update("1");
                }

                return value;
            }
        });

        //TODO 8.提取时间生成watermar
        SingleOutputStreamOperator<TrafficPageViewBean> trafficPageViewWithWMDS = trafficPageViewBySidDS.assignTimestampsAndWatermarks(WatermarkStrategy.<TrafficPageViewBean>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                .withTimestampAssigner(new SerializableTimestampAssigner<TrafficPageViewBean>() {
                    @Override
                    public long extractTimestamp(TrafficPageViewBean element, long recordTimestamp) {
                        return element.getTs();
                    }
                }));

        //TODO 9.分组  开窗  聚合
        WindowedStream<TrafficPageViewBean, Tuple4<String, String, String, String>, TimeWindow> windowedStream = trafficPageViewWithWMDS.keyBy(new KeySelector<TrafficPageViewBean, Tuple4<String, String, String, String>>() {
            @Override
            public Tuple4<String, String, String, String> getKey(TrafficPageViewBean value) throws Exception {
                return new Tuple4<>(
                        value.getIsNew(),
                        value.getAr(),
                        value.getCh(),
                        value.getVc());
            }
        }).window(TumblingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(10)));


        SingleOutputStreamOperator<TrafficPageViewBean> resultDS = windowedStream.reduce(new ReduceFunction<TrafficPageViewBean>() {
            @Override
            public TrafficPageViewBean reduce(TrafficPageViewBean value1, TrafficPageViewBean value2) throws Exception {

                value1.setSvCt(value1.getSvCt() + value2.getSvCt());
                value1.setPvCt(value1.getPvCt() + value2.getPvCt());
                value1.setUvCt(value1.getUvCt() + value2.getUvCt());
                value1.setDurSum(value1.getDurSum() + value2.getDurSum());
                return value1;
            }
        }, new WindowFunction<TrafficPageViewBean, TrafficPageViewBean, Tuple4<String, String, String, String>, TimeWindow>() {
            @Override
            public void apply(Tuple4<String, String, String, String> stringStringStringStringTuple4, TimeWindow window, Iterable<TrafficPageViewBean> input, Collector<TrafficPageViewBean> out) throws Exception {

                //取出数据
                TrafficPageViewBean next = input.iterator().next();

                next.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
                next.setStt(DateFormatUtil.toYmdHms(window.getStart()));

                //写出数据
                out.collect(next);
            }
        });

        //TODO 10.将数据写出
        resultDS.print("-->");
        resultDS.addSink(MyClickHouseUtil.getSinkFunction("insert into dws_traffic_vc_ch_ar_is_new_page_view_window " +
                "values(?,?,?,?,?,?,?,?,?,?,?)"));

        //TODO 11.启动任务
        env.execute();
    }
}
